package cn.witeye.vpais.identify.kit;

public class CosKit {
	private static final int maxScore = -9363600;

	/**
	 * 获取图片特征码sqrt值
	 * @param featureVector 图片特征码
	 * @return
	 */
	public static double featureSquare(float[] featureVector) {
		double featureTmp = 0;
		for (float feature : featureVector) {
			featureTmp += feature * feature;
		}
		return Math.sqrt(featureTmp);
	}

	/**
	 * 比较两个图片的相似度
	 * @param featureVectorA A图特征码
	 * @param featureSquareA A图特征码sqrt值
	 * @param featureVectorB B图特征码
	 * @param featureSquareB B图特征码sqrt值
	 * @return
	 */
	public static double cosDistance(float[] featureVectorA, double featureSquareA, float[] featureVectorB, double featureSquareB) {
		int len = Math.min(featureVectorA.length, featureVectorB.length);

		float tmp1 = 0;
		for (int i = 0; i < len; i++) {
			tmp1 += featureVectorA[i] * featureVectorB[i];
		}
		double dist = tmp1 / (featureSquareA * featureSquareB);
		if (dist < 0 || dist >= 1.001) {
			return maxScore;
		}
		return dist;
	}

}
